import { reactive, inject } from 'vue';

class Store {
  constructor(state, mutations, actions) {
    this.state = state;
    this.mutations = mutations;
    this.actions = actions;
  }

  install(app) {
    // console.log(app);
    //{_uid: 0, _component: {…}, _props: null, _container: null, _context: {…}, …}

    // console.log(this);
    //Store {state: {…}, mutations: {…}, actions: {…}}
    const store = {};

    //返回一个响应式包装后的Store对象
    store.state = reactive(this.state);

    //重写commit方法
    store.commit = (mutationName, payload) => {
      //mutations.plus(state, num){...}
      this.mutations[mutationName](store.state, payload);
    };

    //重写dispatch方法
    store.dispatch = (type, payload) => {
      //actions.plus({commit, state}, num){...}
      this.actions[type]({ commit: store.commit, state: store.state }, payload);
    };

    //向外提供store对象
    app.provide('store', store);
  }
}

export function createStore({ state, mutations, actions }) {
  //返回一个对象用于注册该自定义vuex模块
  return new Store(state, mutations, actions);
}

export function useStore() {
  const store = inject('store');
  return store;
}
